//
//  JXWAppDelegate.m
//  JXWShoppingIPad
//
//  Created by zheng ji on 14-1-15.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "JXWShoppingDelegate.h"
#import "Constants.h"
#import "CommonConfigUtil.h"

//#import "ProdListController.h"
#import "MobClick.h"
@implementation JXWShoppingDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [self initApp];
    [NSThread detachNewThreadSelector:@selector(registerForRemoteNotification) toTarget:self withObject:@"N"];
    
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    
    NSDictionary *payload=[launchOptions  objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    if(nil!=payload){
        NSDictionary *aps=[payload objectForKey:@"aps"];
        NSString *alertMessage=[aps objectForKey:@"alert"];
        if(nil==alertMessage){
            alertMessage=@"" ;
        }
        
        NSString *advtype =[payload objectForKey:@"t"];//advtype
        NSString *objectid =[payload objectForKey:@"i"];
        NSString *objectname =[payload objectForKey:@"n"];
        NSString *batchId =[payload objectForKey:@"b"];//批量
        
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
        if(nil==batchId)batchId=@"";
        
        NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
        
        
        if([@"10" isEqualToString:advtype] || [advtype intValue]==10){//评分
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                  // message:@"亲，喜欢我就给我个评分吧，您 的评价真得很重要！"
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"残忍拒绝"
                                                  otherButtonTitles:@"仁慈给予",nil];
            [alert setTag:998];
            [alert show];
            
        }
        else  if([@"11" isEqualToString:advtype] || [advtype intValue]==11){//分享
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                  //message:@"亲，喜欢我就与朋友们分享吧！"
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"残忍拒绝"
                                                  otherButtonTitles:@"仁慈给予",nil];
            [alert setTag:999];
            [alert show];
            
        }
        else {
            [self pushMessageWithParams:params];
        }
        
        
        [NSThread detachNewThreadSelector:@selector(savePushMsgLog:) toTarget:self withObject:params];
        
    }
    
    
    return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    if(nil!=deviceToken) {
        NSMutableString *strdeviceToken = [[NSMutableString alloc] initWithFormat:@"%@",deviceToken];
        if(nil!=strdeviceToken){
            /*       [strdeviceToken stringByReplacingOccurrencesOfString:@"<" withString:@""];
             [strdeviceToken stringByReplacingOccurrencesOfString:@">" withString:@""];
             [strdeviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
             */
            
            //NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
            [myDefaults setObject:strdeviceToken forKey:@"deviceToken"];
            [myDefaults synchronize];
            
            // NSLog(@"strdeviceToken22:%@",[myDefaults objectForKey:@"deviceToken"]);
            
            
            strdeviceToken=nil;
            
        }
        
        
    }
    
    [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"Y"];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"error:%@",error);
    // [NSThread detachNewThreadSelector:@selector(addMobileUser) toTarget:self withObject:nil];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if(nil==advList){
        advList=[[NSMutableArray alloc] init];
    }
       [NSThread detachNewThreadSelector:@selector(createAdvListThread) toTarget:self withObject:nil];
    //[self createAdvList];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    
    NSDictionary *aps=[userInfo objectForKey:@"aps"];
    NSString *alertMessage=[aps objectForKey:@"alert"];
    if(nil!=alertMessage){
        
        NSString *advtype =[userInfo objectForKey:@"t"];//advtype
        NSString *objectid =[userInfo objectForKey:@"i"];
        NSString *objectname =[userInfo objectForKey:@"n"];
        NSString *batchId =[userInfo objectForKey:@"b"];//批量
        
        
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
        if(nil==batchId)batchId=@"";
        
        
        self.pushPayload=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
        
        [NSThread detachNewThreadSelector:@selector(savePushMsgLog:) toTarget:self withObject:self.pushPayload];
        
        if([@"10" isEqualToString:advtype] || [advtype intValue]==10){//评分
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                  // message:@"亲，喜欢我就给我个评分吧，您 的评价真得很重要！"
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"残忍拒绝"
                                                  otherButtonTitles:@"仁慈给予",nil];
            [alert setTag:998];
            [alert show];
            
        }
        else  if([@"11" isEqualToString:advtype] || [advtype intValue]==11){//分享
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                  // message:@"亲，喜欢我就与朋友们分享吧！"
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"残忍拒绝"
                                                  otherButtonTitles:@"仁慈给予",nil];
            [alert setTag:999];
            [alert show];
            
        }
        
        else {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:alertMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"忽略"
                                                  otherButtonTitles:@"显示",nil];
            [alert setTag:1000];
            [alert show];
            
        }
        
        
        
    }
    
    
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //评分
    if([alertView tag]==998 && buttonIndex == 1 ) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[CommonConfigUtil getAppStoreCommentUrl]]];
    }
    else if([alertView tag]==999 && buttonIndex == 1 ) {
        [self toShare];
    }
    
    else if([alertView tag]==1000 && buttonIndex == 1 ) {
        
        if( nil!=self.pushPayload){
            [self pushMessageWithParams:self.pushPayload];
        }
    }
    
    
}

-(void)pushMessageWithParams:(NSDictionary *)params{
    NSString *advtype =[params objectForKey:@"advtype"];
    // NSString *objectid =[params objectForKey:@"objectid"];
    // NSString *objectname =[params objectForKey:@"objectname"];
    if(nil==advtype)advtype=@"";
    // if(nil==objectid)objectid=@"";
    // if(nil==objectname)objectname=@"";
    
    if(nil!=advtype && ![@"" isEqualToString:advtype]){
        
        UINavigationController* naviController=(UINavigationController*)   self.window.rootViewController;
        [CommonConfigUtil advSelectWithParams:params withUINavigationController:naviController];
        
        
    }
    
}
-(void)savePushMsgLog:(NSDictionary *)params{
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    
    
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    if(nil==openUDID){
        openUDID=@"";
    }
    
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/plus/saveDetailLog/?mobiletype=%@&uuid=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID];
    
    //NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[params objectForKey:@"advtype"]&&![@"" isEqualToString:[params objectForKey:@"advtype"]]){
        [url appendFormat:@"&advtype=%@",[params objectForKey:@"advtype"]];
    }
    
    if(nil!=[params objectForKey:@"objectId"]&&![@"" isEqualToString:[params objectForKey:@"objectId"]]){
        [url appendFormat:@"&objectid=%@",[params objectForKey:@"objectId"]];
    }
    if(nil!=[params objectForKey:@"objectName"]&&![@"" isEqualToString:[params objectForKey:@"objectName"]]){
        [url appendFormat:@"&objectname=%@",[[params objectForKey:@"objectName"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"title"]&&![@"" isEqualToString:[params objectForKey:@"title"]]){
        [url appendFormat:@"&title=%@",[[params objectForKey:@"title"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"batchid"]&&![@"" isEqualToString:[params objectForKey:@"batchid"]]){
        [url appendFormat:@"&batchid=%@",[params objectForKey:@"batchid"]];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    
    reData=nil;
    
    
    
    
    
}



-(void)toShare{
    /*
     if(nil==sharePopover){
     SharePopWindow  *sharePopWindow=[[SharePopWindow alloc] initWithNibName:@"SharePopWindow"  bundle:nil];
     sharePopWindow.parentController=nil;
     sharePopWindow.sharetype=@"8";
     sharePopover = [[UIPopoverController alloc] initWithContentViewController:sharePopWindow];
     [sharePopWindow release];
     
     }
     
     if([sharePopover respondsToSelector:@selector(popoverBackgroundViewClass)]){
     sharePopover.popoverBackgroundViewClass=[CustomPopoverBackgroundView class];
     }
     sharePopover.delegate=self;
     
     
     sharePopover.popoverContentSize = CGSizeMake(240, 240); //弹出窗口大小，如果屏幕画不下，会挤小的。这个值默认是320x1100
     
     
     CGRect popoverRect = CGRectMake((landScape?Landscape_full_width:portrait_full_width)/2-5,(landScape?portrait_full_width:Landscape_full_width)/2-5,10,10);
     
     
     [sharePopover presentPopoverFromRect:popoverRect  //popoverRect的中心点是用来画箭头的，如果中心点如果出了屏幕，系统会优化到窗口边缘
     
     inView:self.tabBarController.view //上面的矩形坐标是以这个view为参考的
     
     permittedArrowDirections:0  //箭头方向
     animated:YES];
     
     */
    
}

- (void)addMobileUser:(NSString *)isSleep{
    
    
    if(nil!=isSleep && [@"Y" isEqualToString:isSleep]){
        [NSThread sleepForTimeInterval:5];
    }
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if(nil==openUDID||[@"" isEqualToString:openUDID]){
        return;
    }
    
    NSString *deviceInfo= [CommonConfigUtil getDeviceInfo];
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/saveMobileuser/?type=%@&uuid=%@&appversion=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID,[CommonConfigUtil getMobileClientApp]];
    
    
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=deviceInfo&&![@"" isEqualToString:deviceInfo]){
        [url appendString:deviceInfo];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    if(nil!=reData && [reData length]>0){
        NSError *error=nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        //NSDictionary *dictionary=[[CJSONDeserializer deserializer] deserializeAsDictionary:reData error:&error];
        
        if(!error){
            NSString  *taobosid=[dictionary objectForKey:@"sid"];//toabosid
            if(nil!=taobosid && ![@"" isEqualToString:taobosid]){
                [myDefaults setObject:taobosid forKey:@"taobosid"];
                [myDefaults synchronize];
            }
            
        }
    }
    
    
    reData=nil;
    
    
    
    
    
    
}

-(void)clearCacheImage{
    
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *path=[CommonConfigUtil getImageLocalPath];
    [fileManager removeItemAtPath:path error:nil];
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    
    
    
    NSString *filestorePath=[CommonConfigUtil getFileLocalPath];
    if(![fileManager fileExistsAtPath:filestorePath ]){
        [fileManager createDirectoryAtPath:filestorePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
}


-(void)initApp{
    
    [MobClick startWithAppkey:[CommonConfigUtil getUmengAppKey] reportPolicy:REALTIME channelId:[CommonConfigUtil getChannelId]];
    

    
    //应用启动时先清理掉本地暂存的图片
    
    [NSThread detachNewThreadSelector:@selector(clearCacheImage) toTarget:self withObject:nil];
    
    
    
    myDefaults=[NSUserDefaults standardUserDefaults];
    if(nil==[myDefaults objectForKey:@"audioPlay"] || [@"" isEqualToString:[myDefaults objectForKey:@"audioPlay"]]){
        [myDefaults setObject:@"N" forKey:@"audioPlay"];
        [myDefaults synchronize];
    }
    
    // [NSThread detachNewThreadSelector:@selector(getCoverInfo) toTarget:self withObject:nil];
    
    [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"N"];
    
    UIInterfaceOrientation t_orientation=[[UIApplication sharedApplication] statusBarOrientation ];
    
    if(t_orientation==UIInterfaceOrientationLandscapeLeft||t_orientation==UIInterfaceOrientationLandscapeRight){
        landScape=YES;
    }else{
        
        landScape=NO;
        
    }
    
}
-(NSMutableArray *)getAdvList{
    if(advList ==nil){
        [self createAdvList];
    }
    return advList;
}
-(void)createAdvList{
    if(nil==advList){
        advList=[[NSMutableArray alloc] init];
    }
    [self createAdvListThread];
    //[NSThread detachNewThreadSelector:@selector(createAdvListThread) toTarget:self withObject:nil];
    
    
}

-(void)createAdvListThread{
    
    
    
    if([CommonConfigUtil checkNetworkReachable]){
		
        NSString *url = [[NSString alloc] initWithFormat:@"%@/ad/list/?category=%@&coverId=%@&appID=%@&app=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getAppAdvType],[CommonConfigUtil getCoverId],[CommonConfigUtil getApp]
                         ,[CommonConfigUtil getApp]];
        
        //  NSLog(@"url:%@",url);
        
        NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                               NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
        
        NSHTTPURLResponse *urlResponse;
        NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
        
        
        if(reData==nil) return ;
        // NSLog(@"reData:%@",reData);
		
        NSError *error=nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        //NSDictionary *dictionary=[[CJSONDeserializer deserializer] deserializeAsDictionary:reData error:&error];
        
        if(!error){
            
            [advList removeAllObjects];
            
            NSArray *advArray=[dictionary objectForKey:@"adList"];
            for(int i=0;nil!=advArray&&i<[advArray count];i++){
                NSMutableDictionary *currentAdv=[[NSMutableDictionary alloc] initWithCapacity:0];
                //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
                
                
                NSString *advid=[[advArray objectAtIndex:i] objectForKey:@"id"];//广告id
                NSString *advtype=[[advArray objectAtIndex:i] objectForKey:@"type"];
                NSString *name=[[advArray objectAtIndex:i] objectForKey:@"name"];//广告名称
                NSString *photo=[[advArray objectAtIndex:i] objectForKey:@"photo"];//图路径
                NSString *fullPath=[[advArray objectAtIndex:i] objectForKey:@"fullPath"];//图路径
                NSString *objectid=[[advArray objectAtIndex:i] objectForKey:@"objectid"];//内容ID
                NSString *objectName=[[advArray objectAtIndex:i] objectForKey:@"objectName"];//内容名称
                NSString *urlparams=[[advArray objectAtIndex:i] objectForKey:@"urlparams"]; //url附加参数
                NSString *loaclPhotoPath;
                
                if(nil==advtype)advtype=@"";
                if(nil==name)name=@"";
                if(nil==fullPath)fullPath=@"";
                if(nil==objectid)objectid=@"";
                if(nil==objectName)objectName=@"";
                if(nil==advid)advid=@"";
                if(nil==urlparams)urlparams=@"";
                
                if(nil==photo){
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_image_%@.jpg",[CommonConfigUtil getImageLocalPath],advid];
                }
                else{
                    NSString *fileName=[photo stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
                    
                    loaclPhotoPath=[NSString stringWithFormat:@"%@/adv_%@",[CommonConfigUtil getImageLocalPath],fileName];//age图
                    
                    //loaclPhotoPath=[NSString stringWithFormat:@"%@/%@",[CommonConfigUtil getFileLocalPath],photo];
                }
                
                [currentAdv setObject:advid forKey:@"advid"];//广告id
                [currentAdv setObject:advtype forKey:@"advtype"];//类型
                [currentAdv setObject:name forKey:@"name"];//类型
                [currentAdv setObject:fullPath forKey:@"image"];
                [currentAdv setObject:objectid forKey:@"objectId"];
                [currentAdv setObject:objectName forKey:@"objectName"];
                [currentAdv setObject:loaclPhotoPath forKey:@"adv_image_local"];
                [currentAdv setObject:urlparams forKey:@"urlparams"];
                
                
                
                [advList addObject:currentAdv];
                
                
                
            }
            
            
            
        }
        
    }
    
    
    
    
}
-(void)registerForRemoteNotification{
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

@end
